package cn.bluedot.tea.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 字符编码过滤器
 * @author Administrator
 *
 */
public class CharterEncodingFilter implements Filter {

	private String encoding;
	
	private boolean isRequestEncoding = false;
	
	private boolean isResponseEncoding = false;
    
	public void init(FilterConfig config) throws ServletException {
		//System.out.println("字符编码过滤器初始化");
		this.encoding = config.getInitParameter("encoding");
		String requestEncoding = config.getInitParameter("requestEncoding");
		String responseEncoding = config.getInitParameter("resposeEncoding");
		
		this.isRequestEncoding = Boolean.parseBoolean(requestEncoding);
		this.isResponseEncoding = Boolean.parseBoolean(responseEncoding);
		
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//System.out.println("字符编码过滤器过滤！");
		String encoding = getEncoding();
		if (encoding != null) {
			if (isRequestEncoding || request.getCharacterEncoding() == null) {
				request.setCharacterEncoding(encoding);
			}
			if (isResponseEncoding) {
				response.setCharacterEncoding(encoding);
			}
		}
		
		chain.doFilter(request, response);
	}

	private String getEncoding() {
		return this.encoding;
	}

	public void destroy() {
		
	}
	
}
